﻿namespace Moly
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Build;
    using Com;

    public class VbSync
    {
        private readonly IProject project;
        private readonly List<string> referencePaths;

        public VbSync(string vbp, string referencePaths)
        {
            Console.WriteLine("Compiling '{0}', using ref path '{1}'", vbp, referencePaths);
            project = VB6.Vb6Project.Create(vbp);
            this.referencePaths = referencePaths.Split(';').Select(s => s.Trim()).ToList();
        }

        public int Build(string outDir)
        {
            FixReferences();
            return Compile(outDir);
        }

        private int Compile(string binDir)
        {
            try
            {
                project.BuildDir = binDir;
                project.Compile(null);
                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return 1;
            }
        }

        private void FixReferences()
        {
            foreach (var dependency in project.Dependencies)
            {
                try
                {
                    var moduleId = FindModuleById(dependency.Name);

                    if (moduleId != null)
                    {
                        dependency.UpdateIf(moduleId);
                    }

                    dependency.VerifyRegistration(true);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("Failed to fix Dependency {0} Error {1}", dependency.Name, ex.Message);
                }
            }
        }

        private ModuleID FindModuleById(string name)
        {
            foreach (var referencePath in referencePaths)
            {
                var files = Directory.GetFiles(referencePath, name,SearchOption.AllDirectories);

                if (files.Any())
                {
                    return new ModuleID(files.First(), null);
                }
            }

            return null;
        }
    }
}